﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Services;
using Cost.Models;
using NBlock.MVCExtensions;
using NBlock.Core.ORM;

namespace Cost.Controllers
{
    public class CommonController : Controller
    {
        #region 构造函数
        private readonly OrgService orgService;
        private readonly UserService userService;

        public CommonController(
            OrgService orgService,
            UserService userService)
        {
            this.orgService = orgService;
            this.userService = userService;
        }
        #endregion

        //
        // GET: /Common/ChooseUser

        /// <summary>
        /// 选择用户
        /// </summary>
        /// <returns></returns>
        public ActionResult ChooseUser()
        {
            return View();
        }

        [HttpPost]
        public JsonResult OrgUserTree(string Id)
        {
            var orgs = orgService.GetOrgsByParentId(Id);
            var users = userService.GetUsersByFullOrgId(Id);
            var treeData = GetSubOrgAndUserTree(Id, orgs, users);
            return Json(treeData);
        }

        [HttpPost]
        public JsonResult QueryUser(string keywords)
        {
            List<UserInfo> list = userService.userRepo
                .FindAll(p => p.UserCode.Contains(keywords) || p.UserName.Contains(keywords))
                .OrderBy(u => u.SeqNo).ToList();
            return Json(list);
        }

        public List<nbJsonTreeNode> GetSubOrgAndUserTree(string parentId, IList<Organization> orgs, IList<UserInfo> users)
        {
            parentId = parentId ?? string.Empty;
            var list = new List<nbJsonTreeNode>();

            // 子部门节点
            foreach (var org in orgs.Where(o => o.ParentId == parentId))
            {
                var Node = new nbJsonTreeNode();
                Node.id = org.Id;
                Node.text = org.OrgName;
                Node.value = org.OrgCode;
                Node.isexpand = org.FullPath.Split(ModelConstant.FULL_PATH_SEPARATOR.ToCharArray()).Length <= 1;
                Node.showcheck = false;
                Node.complete = true;
                Node.ChildNodes = GetSubOrgAndUserTree(org.Id, orgs, users);
                list.Add(Node);
            }

            // 部门下的人员节点
            foreach (var user in users.Where(u => u.OrgId == parentId))
            {
                var Node = new nbJsonTreeNode();
                Node.id = user.Id;
                Node.text = user.UserName;
                Node.value = user.UserCode;
                Node.showcheck = true;
                Node.classes = "user";
                list.Add(Node);
            }

            return list;
        }
    }
}
